package com.kotasoft.iip.integration;

import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;

import com.kotasoft.iip.exception.NonRecoverableServiceException;
import com.kotasoft.iip.exception.RecoverableServiceException;
import com.kotasoft.iip.integration.predicates.ClassPredicate;
import com.kotasoft.iip.model.insurance.Payment;
import com.kotasoft.iip.processor.FeesProcessor;
import com.kotasoft.iip.processor.GenerateMarketOrders;
import com.kotasoft.iip.processor.GenerateSendOrders;
import com.kotasoft.iip.processor.JsonMessageSerializer;
import com.kotasoft.iip.processor.ProcessOrder;
import com.kotasoft.iip.processor.ProcessPayment;
import com.kotasoft.iip.processor.ValorizationOrder;
import com.kotasoft.iip.validation.PaymentValidator;

public class OrderRouteBuilder extends RouteBuilder {

	@Override
	public void configure() throws Exception {

		from(Routes.ORDER_INPUT_QUEUE) //
				.bean(PaymentValidator.class) //
				.bean(FeesProcessor.class) //
				.bean(GenerateMarketOrders.class) //
				.bean(ProcessOrder.class) //
				// Enviamos esta tarea a otra cola para no esperar para generar
				// la respuesta
				.multicast().parallelProcessing().to(Routes.ORDER_PROCESSING_QUEUE) //
				.bean(JsonMessageSerializer.class);

		from(Routes.ORDER_PROCESSING_QUEUE) //
				.delay(3000L) //
				.choice() //
				// Servicios especificos de pagos
				.when(new ClassPredicate(Payment.class)) //
				.bean(ProcessPayment.class) //
				.endChoice() //
				.bean(GenerateSendOrders.class) //
				.to(Routes.ORDER_VALORIZATION_QUEUE);

		from(Routes.ORDER_VALORIZATION_QUEUE) //
				.bean(ValorizationOrder.class);

		from("file://target/input/001").beanRef("mathProvisionLoader");

		from("file://target/input/002") //
				.routeId("SAMPLE_ROUTE_002") //
				// Controlamos exceptiones recuperables
				.onException(RecoverableServiceException.class) //
				.maximumRedeliveries(1) //
				.redeliveryDelay(1000L) //
				.logRetryAttempted(true) //
				.logRetryStackTrace(true) //
				.retryAttemptedLogLevel(LoggingLevel.WARN).end() //
				// Controlamos excepciones no recuperables
				.onException(NonRecoverableServiceException.class) //
				.log(LoggingLevel.ERROR, "Terminal error processing ${in.body}. Failing-fast by forwarding to error destination. ${exception.stacktrace}") //
				.to(Routes.ERROR_QUEUE) //
				.handled(true) //
				.end() //
				.bean(JsonMessageSerializer.class);

	}
}